package com.hckjsec.common.utils;


import com.alibaba.fastjson.JSON;
import com.hckjsec.common.dto.EncryptDto;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author kiki
 * @date 2023/2/28
 * @description
 */
public class AESUtil {


    /**将二进制转换成16进制
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }


    /**将16进制转换为二进制
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1){
            return null;
        }
        byte[] result = new byte[hexStr.length()/2];
        for (int i = 0;i< hexStr.length()/2; i++) {
            int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
            int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 加密
     * @param sSrc 需要加密的字符串
     * 此处使用AES-128-ECB加密模式，key需要为16位。
     * @return
     * @throws Exception
     */
    public static String Encrypt(String sSrc,String sKey) throws Exception {

        // 判断Key是否为16位
        if (sKey.length() != 16) {
            throw new Exception("Key长度不是16位");
        }
        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
        return parseByte2HexStr(encrypted);
        //return new Base64().encodeToString(encrypted);//此处使用BASE64做转码功能，同时能起到2次加密的作用。
    }

    /**
     * 解密
     * @param sSrc 需要解密的字符串
     *  此处使用AES-128-ECB加密模式，key需要为16位。
     * @return
     * @throws Exception
     */
    public static String Decrypt(String sSrc,String sKey){
        byte[] sSrcc = parseHexStr2Byte(sSrc);
        try {
            // 判断Key是否正确
            if (sKey == null) {
                throw new Exception("Key为空null");
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                throw new Exception("Key长度不是16位");
            }
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            //byte[] encrypted1 = new Base64().decode(sSrcc);//先用base64解密
            try {
                byte[] original = cipher.doFinal(sSrcc);
                String originalString = new String(original,"utf-8");
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
         //此处使用AES-128-ECB加密模式，key需要为16位。

        String cKey = "9c7s8gr2bg3ry02i";
        // 需要加密的字串
        String cSrc = "{\"appid\":\"wx31ad03628d4b36e3\",\"openid\":\"oSnUz5a0OPpYEg63634j34RLlqE0\"}";
//        String cSrc = "{}";
        // 加密
        //京娱.公司
        String enString = Encrypt(cSrc,cKey);
        EncryptDto dto = new EncryptDto();
        dto.setData(enString);
        System.out.println(JSON.toJSONString(dto));
        String decrypt = Decrypt("572935C2A6746219690F74328B261525D414E1C03E6A4E783E08B7A77827AD25088197CC6640BC4576A9CB4A1088D7E4BDD9AD24AC5B9924B0AD6DC58A8A32BF9733FCE3CDF3B9CA163D8AAE2D3BE37B05786948CC03606A491C1F39082BD2F26228DF3B7427BCBE68398B3A1793D68064B3A1E13EB0567C2A8B639C717E2E2E18C3FB917FEFB91B1ABFE6EA8E4D5A495150900407A49E5F63FB09640F31D36D18CC653FEF50BE21CD46493996519A7FA0DA93F711BE1DE8294D1302578515EB6E09E8F6B53D95EFCB6A563886B8A73E4385D42F0AF37F9EBDE9F398D3587EF21C6988D88C929F0CC0469DA0C2335B854A4AB72BA10B6EEACD1D8875DD9DDF06DBA33C22C73E89E7B27483CE05771378B673B7365087F2502A5EB11DC1B0483FBFB8A103311C44B69A274EAE9702C1DC736548E0B9AD1486713BA439D858B38A19BAB32825CA43BE7798DBD007284E1AC48175DC3A8BE4021417C057747457E7F3D9D4C22068E99BC33CBC44ADECE7E39E8825FCD5B29F06016766420E3596CEFD5A2709911C48BCF7B64773C1C5A5587D5E4057C5D2B1418035CF39B81A6B17", cKey);
        System.out.println(decrypt);
    }




}

